import {
    StyleSheet, Text, View, TouchableOpacity, FlatList, Image, TextInput, Button, Platform,
    KeyboardAvoidingView, ScrollView
} from 'react-native'
import React, { useEffect, useRef, useState } from 'react'
import { io } from 'socket.io-client'
import AsyncStorage from '@react-native-async-storage/async-storage';
import { getChatList } from '../services/hotTrack.d';
const Socket = (props: any) => {
    interface Message {
        chatname: string,
        chatcontent: string,
    }
    const [messageList, setMessageList] = useState<Message[]>([])
    const [value, setValue] = useState('')
    const flatListRef = useRef<FlatList>(null);

    interface User1 {
        users: string,
        names: string,
        password: string,
        phone: string,
        focusOn: Array<string>,
    }
    const [userOne, setUserOne] = useState<User1>()

    const socket = io('http://192.168.75.194:3001');

    useEffect(() => {
        getUser()
        socket.on('message', obj => {
            setMessageList((prevMessages) => [...prevMessages, obj]);
            console.log(messageList, 3)
        })
        return () => {
            socket.off('message');  // 清理监听器
            socket.disconnect();     // 断开连接
        };
    }, [])
    useEffect(() => {
        getList()
    }, [value])
    const getList = async () => {
        const res: any = await getChatList()
        setMessageList(res.data.data)
    }

    const getUser = async () => {
        const user = await getData('user')
        if (user) {
            setUserOne(user);
        }
    }
    const getData = async (key: string) => {
        try {
            const value: any = await AsyncStorage.getItem(key);
            if (value !== null) {
                setUserOne(JSON.parse(value))
                console.log(value?.names)
            } else {
                console.log('No data found for the key')
            }
            console.log(userOne?.names, 2)
            return value ? JSON.parse(value) : null;
        } catch (error) {
            console.error('Failed to fetch data', error);
        }
    };
    const send = () => {
        if (!userOne?.names || !value)
            return
        let newMessage = {
            username: props.username === userOne?.names ? props.username : userOne?.names,
            message: value,
            // 对方的_id
            _id: props._id,
        };
        socket.emit('message', newMessage)
        setValue('')
    }

    useEffect(() => {
        flatListRef.current?.scrollToEnd({ animated: true });
    }, [messageList])
    return (
        <View style={styles.socketContainer}>
            <View style={styles.socketContent}>
                <FlatList
                    ref={flatListRef}
                    data={messageList}
                    renderItem={({ item }) => (
                        <View style={props.username === item?.chatname ? styles.leftChat : styles.rightChat}>
                            <Image source={{
                                uri: `${item?.chatname === userOne?.names ? 'https://picsum.photos/100' : 'https://picsum.photos/200'}` //换一个

                            }}
                                style={props.username === item?.chatname ? styles.leftChatImg : styles.rightChatImg} />
                            <View>
                                <Text>{item.chatcontent}</Text>
                            </View>
                        </View>
                    )}
                />
            </View>
            <KeyboardAvoidingView
                style={styles.container}
                behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0} // 根据需求调整偏移量
            >
                <View style={styles.content}>
                    {/* 其他内容 */}
                </View>
                <View style={styles.inputContainer}>
                    <TextInput
                        style={styles.input}
                        placeholder="输入信息"
                        value={value}
                        onChangeText={setValue}
                    />
                    <View style={{ width: 70 }}>
                        <Button title='发送' onPress={() => {
                            send()
                        }} />
                    </View>

                </View>
            </KeyboardAvoidingView>
        </View>
    )
}

export default Socket

const styles = StyleSheet.create({
    socketContainer: {
        width: '100%',
        height: '100%',
    },
    socketContent: {
        justifyContent: 'center',
        padding: 20,
        boxSizing: 'border-box',
        marginBottom: 40,
    },
    fixedButton: {
        width: '85%',
        position: 'absolute',
        bottom: 110, // 距离底部 20 像素
        padding: 15,
        borderRadius: 10,
        alignItems: 'center',
        flexDirection: 'row'
    },
    leftChat: {
        flexDirection: 'row',
        alignItems: 'flex-start',
        marginBottom: 10,

    },
    rightChat: {
        flexDirection: 'row-reverse',
        alignItems: 'flex-end',
        marginBottom: 10,
    },
    leftChatImg: {
        width: 40,
        height: 40,
        borderRadius: 20,
        marginRight: 10,

    },
    rightChatImg: {
        width: 40,
        height: 40,
        borderRadius: 20,
        marginLeft: 10,
    },
    container: {
        flex: 1,
    },
    content: {
        flex: 1,
        backgroundColor: '#f0f0f0', // 示例背景
    },
    inputContainer: {
        width: '100%',
        backgroundColor: '#fff',
        padding: 10,
        borderTopWidth: 1,
        borderTopColor: '#ddd',
        flexDirection: 'row',
        alignItems: 'center',
        boxSizing: 'border-box',
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        height: 60,
        justifyContent: 'center',
        zIndex: 10, // 确保覆盖滚动内容
    },
    input: {
        height: 40,
        borderWidth: 1,
        borderColor: '#ddd',
        borderRadius: 20,
        paddingHorizontal: 10,
        width: '80%',
    },

})